import mqtt from 'mqtt/dist/mqtt.js'
import mqttConfig from "@/mqtt/mqttConfig.js"
var clinet;
class mqttUtil {
	constructor({
		ip = mqttConfig.mqtt_ip
	} = {}) {
		this.mqtt_ip = ip
		this.mqtt_options = {
			connectTimeout: 5000,
			clientId: 'qwewqwew',
			username: 'emqx',
			password: 'public',
			clean: false,

		}
		this.topic = ['xiping', 'dakai', "android2can", "pageChange"].concat(mqttConfig.topic);

	}
	connect() {
		var that = this
		var hosts = ''
		// #ifdef H5
		hosts = 'ws://' + this.mqtt_ip
		// #endif
		// #ifdef MP-WEIXIN||APP-PLUS
		hosts = 'wx://' + this.mqtt_ip
		// #endif
		// console.log(hosts);
		if (clinet == null || clinet.connented == false) {
			clinet = mqtt.connect(hosts, this.mqtt_options)
			console.log(clinet);
			clinet.on('connect', function() {
				clinet.subscribe(that.topic, function(err) {
					if (!err) {}
				})
			})
			clinet.on('message', function(topic, message) {
				console.log(topic, message);
				let msgArr = message.toString().split(',')
				console.log(message.toString());
				uni.$emit(`data_${topic}`, {
					msg: message.toString()
				})
			})
		}
		clinet.on('reconnect', function(error) {
			uni.showToast({
				title: '正在重连.....',
				icon: 'none'
			})
		})
		clinet.on('error', function(error) {
			uni.showToast({
				title: '连接失败.....',
				icon: 'none'
			})
		})
		clinet.on('end', function() {
			uni.showToast({
				title: '连接断开...',
				icon: 'none'
			})
		})
	}
	sendMes(topic, msg) {
		console.log(clinet);
		clinet.publish(topic, msg)
	}
	get(callback) {
		clinet.on('message', callback);
	}
	unsubscribe() {
		var that = this
		clinet.unsubscribe(that.topic,
			err => {
				uni.showToast({
					title: '取消订阅成功',
					icon: 'none'
				})
			}
		);
	}
	unconnect() {
		if (!client || !clinet.connected) {
			uni.showToast({
				title: '未连接',
				icon: 'none'
			})
			return;
		}
		clinet.end();
		client = null;
		uni.showToast({
			title: '断开连接',
			icon: 'none'
		})
	}
}
export default mqttUtil